package wens.pig.base.plugin.form;

import kd.bos.armor.core.util.StringUtil;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.mvc.bill.BillView;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import wens.pig.base.service.batch.PigBatchService;

import java.util.HashMap;
import java.util.Map;

/**
 * 提前生成批次档案
 * @author xn-lijunjie
 * @since 2022年07月01日-14:27
 */
public class AddBatchPlugin extends AbstractBillPlugIn {

    private static Map<String,String> map = new HashMap();

    static {
        map.put("wens_ifnewbatch","wens_inbatch");
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        if ("wens_pig_trancolony".equals(this.getView().getFormShowParameter().getFormId())) {
            return;
        }
        String key = e.getProperty().getName();
        String value = map.get(key);
        if(StringUtil.isEmpty(value)){
            return;
        }
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        boolean aBoolean = dataEntity.getBoolean(key);
        if(aBoolean) {
            OperationResult result = this.getView().invokeOperation("save");
            if(result.isSuccess()){
                ((BillView) this.getView()).getClientProxy().removeAction("ShowNotificationMsg");
                DynamicObject dynamicObject = PigBatchService.getInstance().createPigBatchData(this.getModel().getDataEntity(true));
                SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
                this.getModel().setValue(value, dynamicObject);
            }
        }else {
            DynamicObject dynamicObject = dataEntity.getDynamicObject(value);
            if(null != dynamicObject){
                DeleteServiceHelper.delete(dynamicObject.getDataEntityType(),new Object[]{dynamicObject.getPkValue()});
            }
            this.getModel().setValue(value, null);
        }
    }
}
